package com.google.precinct.server;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class KeyUtils {

	public static final String kndAddress = "Address";

	static Key precinctInfo(String region) {
		return KeyFactory.createKey("R", region);
	}

	static Key precinctInfoProvince(Key regionKey, String province) {
		return KeyFactory.createKey(regionKey, "P", province);
	}

	static Key precinctInfoCity(Key provinceKey, String city) {
		return KeyFactory.createKey(provinceKey, "C", city);
	}

	static Key precinctInfoCluster(Key cityKey, long clusterId) {
		return KeyFactory.createKey(cityKey, "Cluster", clusterId);
	}

	static Key precinctInfoPrecinct(Key cityKey, String precinctNo) {
		return KeyFactory.createKey(cityKey, "Precinct", precinctNo);
	}

	public static Key addressInfo(Key cityKey, String address) {
		if (address.length() > 400) {
			address = address.substring(0, 400);
		}
		return KeyFactory.createKey(cityKey, "Address", address);
	}

	public static Key userIP(String ipaddress) {
		return KeyFactory.createKey("IP", ipaddress);
	}

	public static Key userMarker(Key userIPKey, String userMarker) {
		return KeyFactory.createKey(userIPKey, "UM", userMarker);
	}

	static Key cityCompletion(String cityName, int chars) {
		if (chars <= 0) {
			return KeyFactory.createKey("CityCmplte", "DEFAULT");
		}
		String leadChar = cityName.toUpperCase();
		if (cityName.length() > chars) {
			leadChar = cityName.substring(0, chars).toUpperCase();
		}
		return KeyFactory.createKey("CityCmplte", leadChar);
	}

	static String memcache(Key key) {
		if (key.getKind().equals("CityCmplte")) {
			return "City-" + key.getName();
		}
		throw new IllegalArgumentException("Invalid Key sent!");
	}

	 static String cleanProvinceName(String province) {
		return province.replaceAll("  ", " ");
	}

	 static String cleanCityName(String city) {
		return city.replaceAll("(POB)", "").replaceAll("  ", " ");
	}


}
